import logging
import time
from enum import Enum
import urllib.parse
from flask import request, Response
from flask_restful import Resource, reqparse

from app.commons.config import get_current_time
from app.commons.pagination import get_page
from app.commons.redis_session import redis_con
from app.commons.check_token import checkIfLogin
from app.commons.ma import ma


class ListReqType(Enum):
    ViewList = 1
    Delete = 2


class ListRequestArgs(ma.Schema):
    data = ma.String()
    page = ma.Integer()
    limit = ma.Integer()
    type = ma.Integer()
    date = ma.String()


class ListView(Resource):

    @staticmethod
    def make_blacklist_key(v):
        postfix = int(v) % 10
        return "blacklist_" + str(postfix)

    def get(self):
        try:
            host="pjsnkr"
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            userid=checkIfLogin(cookie)
            if userid:
                query_args = ListRequestArgs().dump(request.args)
                request_type = int(query_args["type"])
                r = redis_con()
                if request_type == ListReqType.ViewList.value:
                    page = int(query_args["page"])
                    limit = int(query_args["limit"])
                    result = r.zrange("blacklist_total", start=0, end=-1, desc=True, withscores=True)
                    resp = []
                    for i in result:
                        local_time = time.localtime(int(i[1]))
                        timestr = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
                        resp.append({"data": i[0], "ctime": timestr})
                    data, total_size = get_page(page, limit, resp)
                    logging.warning(
                        "get blaklist, key=%s, value=%s, page=%s, limit=%s" % ("blacklist_total", data, page, limit))
                    return {"code": 0, "msg": "", "count": total_size, "data": data}
                elif request_type == ListReqType.Delete.value and userid==host:
                    data = str(query_args["data"])
                    r.zrem("blacklist_total", data)
                    r.zrem(self.make_blacklist_key(data), data)
                    return {"success": "true"}
                else:
                    return {"success": "false", "err_msg": "wrong request type"}
            else:
                return {"success": "false", "err_msg": "no login"}
        except:
            logging.warning("fail fetching blacklist")
            return {"success": "false","code": 0}

    def post(self):
        try:
            host = "pjsnkr"
            cookie = urllib.parse.unquote(str(request.cookies.get('pj_login')))
            userid=checkIfLogin(cookie)
            if userid and str(userid)==host:
                recv_data = request.get_json()
                data_list=[recv_data["number"]]   #暂时支持单个元素
                r = redis_con()
                ctime = get_current_time('s')
                for value in data_list:
                    key = self.make_blacklist_key(value)
                    r.zadd("blacklist_total", {str(value): ctime})
                    logging.warning("add blaklist, key=%s, value=%s" % ("blacklist_total", value))
                    r.zadd(key, {str(value): ctime})
                    logging.warning("add blaklist, key=%s, value=%s" % (key, value))
                return {"success": "true"}
            else:
                return {"success": "false", "err_msg": "no login"}
        except:
            logging.warning("fail adding blacklist")
            return {"success": "false"}
